import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isString from "lodash/isString";
import _isObject from "lodash/isObject";
import _isEmpty from "lodash/isEmpty";
import _indexOf from "lodash/indexOf";

var _dec, _dec2, _class;

/**
 * AvatarUploadModal.js - 头像上传模态框
 * @description
 * @date 2018/11/15
 */
import React from 'react';
import { Button, Icon, Modal, Upload } from 'antd';
import Cropper from 'react-cropper';
import 'cropperjs/dist/cropper.css';
import { Bind } from 'lodash-decorators';
import intl from 'utils/intl';
import notification from 'utils/notification';
import { CPAAS_FILE, BKT_PUBLIC } from 'utils/config';
import { getCurrentOrganizationId, isTenantRoleLevel } from 'utils/utils';
import styles from "../index.less?modules";
var Dragger = Upload.Dragger;
var STORAGE_UNIT = {
  KB: 1024,
  MB: 1024 * 1024,
  GB: 1024 * 2014 * 1024
};

function isJSON(str) {
  var result;

  try {
    result = JSON.parse(str);
  } catch (e) {
    return false;
  }

  return _isObject(result) && !_isString(result);
}

var AvatarUploadModal = (_dec = Bind(), _dec2 = Bind(), (_class = /*#__PURE__*/function (_React$PureComponent) {
  _inherits(AvatarUploadModal, _React$PureComponent);

  var _super = _createSuper(AvatarUploadModal);

  function AvatarUploadModal() {
    var _this;

    _classCallCheck(this, AvatarUploadModal);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = {
      fileList: [],
      file: null,
      avatarPath: '',
      limitData: {},
      currentTenantId: getCurrentOrganizationId()
    };
    _this.cropper = void 0;
    return _this;
  }

  _createClass(AvatarUploadModal, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.handleSearch();
    }
  }, {
    key: "handleSearch",
    value: function handleSearch() {
      var _this2 = this;

      var _this$props = this.props,
          dispatch = _this$props.dispatch,
          organizationId = _this$props.organizationId;
      dispatch({
        type: 'userInfo/fetchEnabledFile',
        payload: {
          tenantId: organizationId,
          bucketName: BKT_PUBLIC,
          directory: 'ciam02'
        }
      }).then(function (res) {
        if (res) {
          _this2.setState({
            limitData: res
          });
        }
      });
    }
  }, {
    key: "handleCancel",
    value: function handleCancel() {
      var onCancel = this.props.onCancel;
      onCancel();
      this.setState({
        fileList: [],
        file: null
      });
    }
    /**
     * 图片裁剪，获取图片的blob格式
     */

  }, {
    key: "handleAvatarCrop",
    value: function handleAvatarCrop() {
      var dispatch = this.props.dispatch;
      var imgCanvas = this.cropper.getCroppedCanvas({
        width: 256,
        height: 256,
        imageSmoothingQuality: 'high'
      }); // IE toBlob兼容方案，手动实现toBlob，兼容IE10及以上

      if (!HTMLCanvasElement.prototype.toBlob) {
        Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
          value: function value(callback, type, quality) {
            // atob将编码为base64后的图片数据解码为二进制数据
            var binStr = atob(this.toDataURL(type, quality).split(',')[1]);
            var len = binStr.length; // 使用二进制数组存放数据

            var arr = new Uint8Array(len);

            for (var i = 0; i < len; i++) {
              // 将指定位置的数据设置为Unicode编码，存放在二进制数组中
              arr[i] = binStr.charCodeAt(i);
            } // 最后返回Blob类型的数据


            callback(new Blob([arr], {
              type: type || 'image/png'
            }));
          }
        });
      }

      imgCanvas.toBlob(function (blob) {
        dispatch({
          type: 'userInfo/updateState',
          payload: {
            imgFormData: blob
          }
        });
      });
    }
    /**
     *beforeUpload 上传之前进行类型检测
     * @param {Object} file 文件对象
     */

  }, {
    key: "beforeUpload",
    value: function beforeUpload(file) {
      this.setState(function (_ref) {
        var fileList = _ref.fileList;
        return {
          fileList: [].concat(_toConsumableArray(fileList), [file]),
          file: file
        };
      });
      this.props.dispatch({
        type: 'userInfo/updateState',
        payload: {
          imgFormData: file
        }
      });
      return false;
    }
    /**
     * 选择图片后，将图片转换为base64格式预览
     * @param {object} info 文件数据对象，包含file，fileList
     */

  }, {
    key: "handleImgChange",
    value: function handleImgChange(info) {
      var dispatch = this.props.dispatch;
      var reader = new FileReader();
      reader.readAsDataURL(info.file);

      reader.onload = function () {
        dispatch({
          type: 'userInfo/updateState',
          payload: {
            uploadImgPreviewUrl: reader.result,
            uploadImgName: info.file.name
          }
        });
      };
    }
    /**
     * 校验上传参数
     * 使用时: 如果Boolean(返回的数据), 则不做限制
     */

  }, {
    key: "validateUploadParams",
    value: function validateUploadParams() {
      var _this$state = this.state,
          file = _this$state.file,
          limitData = _this$state.limitData;
      var fileFormat = limitData.fileFormat,
          storageSize = limitData.storageSize,
          storageUnit = limitData.storageUnit;

      if (!fileFormat && !storageSize) {
        // 如果没有查询到桶配置, 那么就不做限制;
        return;
      }

      var flag = true;
      var message;

      if (fileFormat) {
        var fileType = fileFormat.split(',').map(function (item) {
          return "image/".concat(item);
        });

        if (fileType.indexOf('image/jpg') > -1) {
          fileType.push('image/jpeg');
        }

        flag = _indexOf(fileType, file.type) > -1;
        message = flag ? '' : intl.get('ciam.userInfo.view.message.fileTypeError').d('文件类型不支持');
      }

      if (storageSize && flag) {
        // 表示文件大小上限，单位：KB
        var fileSize = STORAGE_UNIT[storageUnit] * storageSize;
        flag = fileSize > file.size;
        message = flag ? '' : intl.get('cpaas.common.upload.error.size.custom', {
          fileSize: "".concat(storageSize).concat(storageUnit)
        }).d("\u4E0A\u4F20\u6587\u4EF6\u5927\u5C0F\u4E0D\u80FD\u8D85\u8FC7: ".concat(storageSize).concat(storageUnit));
      }

      return message;
    }
    /**
     * 保存裁剪的图片
     */

  }, {
    key: "handleCutAvatar",
    value: function handleCutAvatar() {
      var _this3 = this;

      var fileList = this.state.fileList;
      var _this$props2 = this.props,
          dispatch = _this$props2.dispatch,
          imgFormData = _this$props2.imgFormData,
          uploadImgName = _this$props2.uploadImgName,
          organizationId = _this$props2.organizationId,
          onCancel = _this$props2.onCancel;
      dispatch({
        type: 'userInfo/updateState',
        payload: {
          imgUploadStatus: 'uploading'
        }
      });

      if (fileList.length > 1) {
        fileList.pop();
      } // 判断是否有上传配置，有的话对上传的文件类型和大小作限制，否则都不限制


      var message = this.validateUploadParams();

      if (message) {
        notification.error({
          message: message
        });
        dispatch({
          type: 'userInfo/updateState',
          payload: {
            imgUploadStatus: 'waiting'
          }
        });
        return;
      }

      dispatch({
        type: 'userInfo/uploadAvatar',
        payload: {
          organizationId: organizationId,
          image: imgFormData,
          uploadImgName: uploadImgName,
          bucketName: BKT_PUBLIC,
          directory: 'ciam02'
        }
      }).then(function (res) {
        if (isJSON(res) && JSON.parse(res).failed) {
          notification.error({
            description: JSON.parse(res).message
          });
        } else if (res) {
          _this3.setState({
            avatarPath: res
          }, function () {
            dispatch({
              type: 'userInfo/saveAvatar',
              payload: res
            }).then(function (result) {
              if (result) {
                notification.success({
                  message: intl.get('ciam.userInfo.view.message.updateSuccess').d('头像保存成功')
                });

                _this3.setState(_objectSpread(_objectSpread({}, _this3.state), {}, {
                  fileList: [],
                  file: null
                }));

                onCancel(); // eslint-disable-next-line no-underscore-dangle

                var state = window.dvaApp._store.getState();

                var _state$userInfo = state.userInfo,
                    userInfo = _state$userInfo === void 0 ? {} : _state$userInfo;
                dispatch({
                  type: 'userInfo/updateState',
                  payload: {
                    userInfo: _objectSpread(_objectSpread({}, userInfo.userInfo), {}, {
                      imageUrl: res
                    })
                  }
                });
                dispatch({
                  type: 'user/updateCurrentUser',
                  payload: {
                    imageUrl: res
                  }
                });
              }
            });
          });
        }
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this4 = this;

      var _this$props3 = this.props,
          avatarVisible = _this$props3.avatarVisible,
          imgUploadStatus = _this$props3.imgUploadStatus,
          loading = _this$props3.loading,
          uploadImgPreviewUrl = _this$props3.uploadImgPreviewUrl,
          userInfo = _this$props3.userInfo,
          onOk = _this$props3.onOk;
      var _this$state2 = this.state,
          fileList = _this$state2.fileList,
          limitData = _this$state2.limitData,
          currentTenantId = _this$state2.currentTenantId;
      var fileFormat = limitData.fileFormat,
          storageSize = limitData.storageSize,
          storageUnit = limitData.storageUnit;
      var displayFlag = false;
      var typeFlag = false;

      if (!_isEmpty(limitData)) {
        displayFlag = true;

        if (limitData.fileFormat !== '') {
          typeFlag = true;
        }
      }

      return /*#__PURE__*/React.createElement(Modal, {
        visible: avatarVisible,
        maskClosable: false,
        title: intl.get('ciam.userInfo.view.message.changeAvatar').d('更换头像'),
        width: 485,
        onOk: onOk,
        onCancel: this.handleCancel,
        footer: [/*#__PURE__*/React.createElement(Button, {
          key: "back",
          onClick: this.handleCancel
        }, intl.get('cpaas.common.button.cancel').d('取消')), /*#__PURE__*/React.createElement(Button, {
          key: "submit",
          type: "primary",
          onClick: function onClick() {
            return _this4.handleCutAvatar();
          },
          disabled: fileList.length === 0,
          loading: imgUploadStatus === 'uploading' || loading
        }, intl.get('cpaas.common.button.save').d('保存'))]
      }, fileList.length === 0 ? /*#__PURE__*/React.createElement(Dragger, {
        className: styles['avatar-uploader'],
        showUploadList: false,
        beforeUpload: function beforeUpload(file) {
          return _this4.beforeUpload(file);
        },
        onChange: function onChange(info) {
          return _this4.handleImgChange(info);
        },
        name: "image",
        action: "".concat(CPAAS_FILE, "/v1/").concat(isTenantRoleLevel() ? "".concat(currentTenantId, "/") : '', "files/byte"),
        data: {
          imagePath: userInfo.imageUrl
        },
        accept: "image/jpeg,image/jpg,image/png,image/gif,image/bmp"
      }, /*#__PURE__*/React.createElement("p", {
        className: "ant-upload-drag-icon"
      }, /*#__PURE__*/React.createElement(Icon, {
        type: "inbox"
      })), /*#__PURE__*/React.createElement("p", {
        className: "ant-upload-text"
      }, intl.get('ciam.userInfo.view.message.uploadTips').d('点击或将图片拖到此区域上传图片')), displayFlag && /*#__PURE__*/React.createElement("p", {
        className: "ant-upload-hint"
      }, typeFlag && intl.get('ciam.userInfo.view.message.uploadType', {
        uploadType: fileFormat
      }).d("\u652F\u6301".concat(fileFormat, "\u683C\u5F0F\uFF0C")), intl.get('cpaas.common.upload.error.size.custom', {
        fileSize: "".concat(storageSize).concat(storageUnit)
      }).d("\u4E0A\u4F20\u6587\u4EF6\u5927\u5C0F\u4E0D\u80FD\u8D85\u8FC7: ".concat(storageSize).concat(storageUnit)))) : /*#__PURE__*/React.createElement("div", {
        className: styles.uploader
      }, /*#__PURE__*/React.createElement("div", {
        className: styles['avatar-upload']
      }, /*#__PURE__*/React.createElement("div", {
        className: styles['avatar-crop-wrap']
      }, /*#__PURE__*/React.createElement(Cropper, {
        viewMode: 1,
        preview: ".img-preview",
        className: styles['avatar-crop'],
        ref: function ref(ele) {
          _this4.cropper = ele;
        },
        src: uploadImgPreviewUrl,
        aspectRatio: 1 / 1,
        zoomable: false,
        movable: false,
        guides: false,
        crop: function crop() {
          return _this4.handleAvatarCrop();
        }
      })), /*#__PURE__*/React.createElement("div", {
        className: styles['avatar-preview-wrap']
      }, /*#__PURE__*/React.createElement("div", null, intl.get('ciam.userInfo.view.message.preview').d('预览')), /*#__PURE__*/React.createElement("div", {
        className: styles.preview
      }, /*#__PURE__*/React.createElement("div", {
        className: "img-preview",
        style: {
          width: 100,
          height: 100
        }
      }), /*#__PURE__*/React.createElement("div", null, "100 * 100")), /*#__PURE__*/React.createElement("div", {
        className: styles.preview
      }, /*#__PURE__*/React.createElement("div", {
        className: "img-preview",
        style: {
          width: 64,
          height: 64
        }
      }), /*#__PURE__*/React.createElement("div", null, "64 * 64")), /*#__PURE__*/React.createElement("div", {
        className: styles.preview
      }, /*#__PURE__*/React.createElement("div", {
        className: "img-preview",
        style: {
          width: 24,
          height: 24
        }
      }), /*#__PURE__*/React.createElement("div", null, "24 * 24")))), /*#__PURE__*/React.createElement(Upload, {
        className: styles['avatar-uploader'],
        showUploadList: false,
        beforeUpload: function beforeUpload(file) {
          return _this4.beforeUpload(file);
        },
        onChange: function onChange(info) {
          return _this4.handleImgChange(info);
        },
        name: "image",
        action: "".concat(CPAAS_FILE, "/v1/").concat(isTenantRoleLevel() ? "".concat(currentTenantId, "/") : '', "files/byte"),
        data: {
          imagePath: userInfo.imageUrl
        },
        accept: "image/jpeg,image/jpg,image/png,image/gif,image/bmp"
      }, /*#__PURE__*/React.createElement(Button, {
        style: {
          marginTop: 10
        }
      }, /*#__PURE__*/React.createElement(Icon, {
        type: "upload"
      }), intl.get('ciam.userInfo.view.option.selectPic').d('重新上传')))));
    }
  }]);

  return AvatarUploadModal;
}(React.PureComponent), (_applyDecoratedDescriptor(_class.prototype, "handleSearch", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "handleSearch"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleCancel", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "handleCancel"), _class.prototype)), _class));
export { AvatarUploadModal as default };